package com.myblog.service.impl;

import com.myblog.constant.CodeType;
import com.myblog.mapper.UserMapper;
import com.myblog.model.Role;
import com.myblog.model.User;
import com.myblog.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    /**
     * 添加角色权限，通过security验证用户登录
     * @param phone
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        //查询用户信息
        User user = userMapper.selectUserByPhone(phone);
        //判断用户是否为空
        if(Objects.isNull(user)){
            throw new UsernameNotFoundException(CodeType.USERNAME_NOT_EXIST.name());
        }
        //当用户不为空时（ROLE_USER）
//        System.out.println(userMapper.queryRolesByPhone(phone));
        List<Role> roles = userMapper.queryRolesByPhone(phone);
        user.setRoles(roles);

        //记录用户登录系统的时间
        TimeUtil timeUtil = new TimeUtil();
        String formatDateForSix = timeUtil.getFormatDateForSix();
        //更新用户登陆时间
        userMapper.updateRecentlyLanded(user.getUsername(), formatDateForSix);
        //添加角色权限
        ArrayList<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (Role role : user.getRoles()) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),authorities);
    }
}
